package com.ruoyi.robot.service;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.robot.domain.DeepSeekBackBody;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

@Service
public class DeepSeekClient {

    private static final String API_KEY = "sk-2c62c30bdcbd43daa77720384bcc75ea";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";

    public  String  getAnswer(String question) {
        String trueAnswer = "遇到问题,稍后重试!";
        String requestBody = """
            {
                "model": "deepseek-chat",
                "messages": [
                    {"role": "user", "content": " """ + question + """
                    "}
                ],
                "temperature": 0.7
            }
            """;
        // 请求参数示例（根据实际API文档调整）


        try {
            HttpClient client = HttpClient.newBuilder()
                    .version(HttpClient.Version.HTTP_2)
                    .connectTimeout(Duration.ofSeconds(10))
                    .build();

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            HttpResponse<String> response = client.send(
                    request, HttpResponse.BodyHandlers.ofString());

            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Response Body: " + response.body());

            DeepSeekBackBody deepSeekBackBody = JSON.parseObject(response.body(), DeepSeekBackBody.class);
            StringBuilder answer = new StringBuilder("");
            deepSeekBackBody.getChoices().forEach(choice -> {
//                System.out.println("Message Content: " + choice.getMessage().getContent());
                answer.append(choice.getMessage().getContent());
            });
            trueAnswer = answer.toString();
            System.out.println("Message Content: " + answer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return trueAnswer;
    }
}